package cn.ryanpenn.es.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * SpringDao
 *
 * @author pennryan
 */
@Component
public class SpringDao {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    public boolean create() {
        return jdbcTemplate.update("DROP TABLE IF EXISTS TEST;" +
                "CREATE TABLE TEST(ID INT PRIMARY KEY, first_name VARCHAR(255),last_name VARCHAR(255));" +
                "INSERT INTO TEST VALUES(1, 'First', 'Last');"
                , new HashMap<>(0)) != -1;
    }

    public Person getById(int id) {
        return jdbcTemplate.queryForObject(
                "select id, first_name, last_name from TEST where id = :id",
                new HashMap<String, Integer>(1) {{
                    put("id", 1);
                }},
                new RowMapper<Person>() {
                    @Override
                    public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Person o = new Person();
                        o.setId(rs.getInt(1));
                        o.setFirstName(rs.getString(2));
                        o.setLastName(rs.getString(3));
                        return o;
                    }
                });
    }

}
